<?php
/**
 * 使用示例
 * @author jepin
 * @version 1.0
 * create Date 2014-08-11
 */
class YlURLTaglib {
	
        private $_dbPrefix = 'yl_';
    
	public function __construct() {
		C(include SITE_PATH.'/extends/taglib/tagarr.php');
                $dbPrefix = C('db_prefix');
                !empty($dbPrefix) && $this->_dbPrefix = $dbPrefix;
	}
	
	public function parse($content, $domain) {
		$config = include SITE_PATH .'/apps/cms/Conf/textlink.php' ;
		if (!$config) {
			return  $content ;
		}
		$openlink    = $config[ 'openlink'];   // 是否开启
		$openkeyword = $config[ 'openkeyword']; //是否设置栏目为关键字
		$linkcode    = $config[ 'linkcode'];   //链接内容
		$linkmun     = $config[ 'linknum'];    //替换次数
		// 是否开启替换
		if(!$openlink){
			return $content;
		}
		// 替换链接功能
        if(false === ($textlink = S('cache_textlink'))){
            $textlink = model('TextLink')->order('link_id desc')->select();
            S('cache_textlink', $textlink, 600);
        }
		foreach($textlink  as $link){
			$url=str_replace('{0}',$link[ 'url' ],$linkcode);
			$url=str_replace('{1}',$link[ 'text' ],$url);
                        //匹配文章中自带的a链接
                        preg_match_all("/<a.*?<\/a>/is",$content,$matched);
                        //用{TEMP_REPLACE}替换文章自带的a标签
                        $content = preg_replace("/<a.*?<\/a>/is",'{TEMP_REPLACE}',$content);
                        $content = preg_replace('/'.$link['text'].'/',$url,$content,$linkmun);
//                        $content = str_replace($link['text'], $url, $content, $linkmun);
                        //将{TEMP_REPLACE}替换回相应的a标签
                        foreach($matched[0] as $v){
                            $content = preg_replace('/{TEMP_REPLACE}/', $v, $content, 1);
                        }		
		}
		// 是否栏目替换
		if($openkeyword){
			$sqlstr='SELECT  (case when url <> "" then url ';
			$sqlstr.=' when createurl <> "" then createurl';
			$sqlstr.=' else (concat(s.domain,"/",replace(catenaming,"{cateid}",id))) ';
			$sqlstr.='end)  as url,cname   ';
			$sqlstr.=' from '.$this->_dbPrefix.'cms_category c LEFT JOIN  '.$this->_dbPrefix.'cms_site s  on  c.siteid=s.siteid';
			if(false === ($clum_link = S('cache_sql_'.$sqlstr))){
				$clum_link =M()->query($sqlstr);
				S('cache_sql_'.$sqlstr, $clum_link, 600);
			}
				
			foreach($clum_link  as $link){
				$url=str_replace('{0}',$link[ 'url' ],$linkcode);
				$url=str_replace('{1}',$link[ 'cname' ],$url);
				//匹配文章中自带的a链接
				preg_match_all("/<a.*?<\/a>/is",$content,$matched);
				//用{TEMP_REPLACE}替换文章自带的a标签
				$content = preg_replace("/<a.*?<\/a>/is",'{TEMP_REPLACE}',$content);
				$content = preg_replace('/'.$link['cname'].'/',$url,$content,$linkmun);
				//将{TEMP_REPLACE}替换回相应的a标签
				foreach($matched[0] as $v){
					$content = preg_replace('/{TEMP_REPLACE}/', $v, $content, 1);
				}
			}
		}
		return $content;
	}
}